<template>
  <transition name="msg-fade" mode="out-in">
    <div class="message flex-box" :class="type" v-if="visible">
      <p class="content">{{content}}</p>
    </div>
  </transition> 
</template>

<script>
const Msg = {
  name: 'message',
  data() {
    return {
      visible: false,
      type: '',
      content: ''
    }
  },
  install(Vue) {
    Vue.prototype.$msg = config => {
      //通过原型注册一个方法
      const MessageConstructor = Vue.extend(Msg) //生成一个Vue子类，子类就是这个组件
      let obj = {}
      obj.content = config.content ? config.content : config
      obj.type = config.type ? config.type : 'msg'
      const instance = new MessageConstructor({ data: obj }) //生成该子类的实例
      instance.vm = instance.$mount() //将该实例手动挂载
      document.body.appendChild(instance.vm.$el) //将实例挂载到body上
      instance.vm.visible = true
    }
  },
  watch: {
    visible(v) {
      if (v) {
        setTimeout(() => {
          this.onClose()
        }, 3000)
      }
    }
  },
  methods: {
    onClose() {
      this.visible = false
    },
    show() {
      this.visible = true
    }
  }
}
export default Msg
</script>
<style lang="scss">
.message {
  position: fixed;
  width: 100%;
  top: 60%;
  opacity: 1;
  z-index: 9999999;
  height: auto;
  box-sizing: border-box;
  &.msg {
    p {
      background: rgba($color: #000, $alpha: 0.75);
      border: 1px solid #333;
      border-radius: 4px;
      color: #fff;
    }
  }
  &.success {
    p {
      background: #ebf8f2;
      border: 1px solid #ebf8f2;
      border-radius: 4px;
    }
  }
  &.warn {
    p {
      background: #fffaeb;
      border: 1px solid #fccca7;
      border-radius: 4px;
    }
  }
  &.error {
    p {
      background: #fef3eb;
      border: 1px solid #ffe9a7;
      border-radius: 4px;
    }
  }
  .content {
    padding: 15px;
    display: inline-block;
    font-size: 16px;
    line-height: 20px;
    min-width: 220px;
    max-width: 300px;
    text-align: center;
    color: rgba(0, 0, 0, 0.65);
    letter-spacing: 0;
  }
}

.msg-fade-enter-active,
.msg-fade-leave-active {
  transition: all 0.3s;
}
.msg-fade-enter,
.msg-fade-leave-to {
  opacity: 0;
  transform: translate3d(0, 30%, 0);
}
</style>
